package br.com.guiav6.sisguia.dao.hibernate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import br.com.guiav6.sisguia.bean.AnuncioBean;
import br.com.guiav6.sisguia.dao.EmpresaDao;
import br.com.guiav6.sisguia.entity.Empresa;
import br.com.guiav6.sisguia.repository.hibernate.AbstractDaoHibernate;

@Repository("empresaDao")
public class EmpresaDaoHibernate extends AbstractDaoHibernate<Long, Empresa> implements EmpresaDao {

	@Override
	public List<Empresa> findEmpresaByServicoEspecialidadeLocal(AnuncioBean bean, Integer idBairro) {
		Map<String, Object> params = new HashMap<String, Object>();
		
		StringBuilder sql = new StringBuilder("select distinct(e) from Empresa e");
		sql.append(" inner join e.tipoServicoEmpresaList tse");
		sql.append(" where tse.tipoServico.id = :idServico");
		params.put("idServico", bean.getIdServico());
		
		if(idBairro > 0){
			sql.append(" and e.endereco.bairro.id = :bairro");
			params.put("bairro", idBairro.longValue());
		}
		
		if(bean.getIdEspecialidade() != null){
			sql.append(" and tse.especialidade.id = :idEspecialidade");
			params.put("idEspecialidade", bean.getIdEspecialidade());
		}
		
		TypedQuery<Empresa> q = getEntityManager().createQuery(sql.toString(), Empresa.class);
		
		for(String key: params.keySet()){
			q.setParameter(key, params.get(key));
		}
		
		return q.getResultList();
	}

	@Override
	public Empresa findByCnpjCpf(String cnpjCpf) {
		TypedQuery<Empresa> q = getEntityManager().createQuery("from Empresa e where e.cnpjCpf = :cnpjCpf", Empresa.class);
		q.setParameter("cnpjCpf", cnpjCpf);
		try{
			return q.getSingleResult();
		}catch (NoResultException nre) {
			return null;
		}
	}

	@Override
	public List<Empresa> findEmpresasByBloco(String bloco, String cep) {
		TypedQuery<Empresa> q = getEntityManager().createQuery("from Empresa e where e.endereco.bloco = :bloco and e.endereco.cep = :cep", Empresa.class);
		q.setParameter("bloco", bloco);
		q.setParameter("cep", cep);
		
		return q.getResultList();
	}

}